import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/views/common/Home';
import Contact from '../views/chat/index.vue';
import alipay from '../views/purchaseOrder/alipay.vue';
import axios from 'axios'

import {
    saveObjArr,
    getObjArr
} from "@/utils/ruoyi.js"
import {
    dynamicRoute
} from "./dynamicRoute.js"
import {
    getMenus
} from "@/api/common"
import {
    getToken
} from '@/utils/auth'
Vue.use(Router)
// 配置项目中没有涉及权限的公共路由
export const constantRoutes = [{
        path: "/",
        component: Layout,

        redirect: "dashboard",
        index: '/dashboard',
        meta: {
            title: '系统首页',
        },
        icon: 'el-icon-lx-home',
        children: [{
            path: "/dashboard",
            name: "dashboard",
            sort: "系统首页",
            meta: {
                name: '系统首页'
            },
            component: () =>
                import('@/views/page/Dashboard'),
            index: '/dashboard',
        }, ]
    },
    {
        path: '/login',
        component: () =>
            import('@/views/page/Login'),
        hidden: true
    },
    {
        path: '/chat',
        component: () =>
            import('@/views/chat/index'),
        hidden: true
    },
    {
        path: '/alipay',
        name: 'alipay',
        component: alipay,
        // component: () =>
        //     import ('@/views/common/chat/index'),
        hidden: true
    },
    {
        path: '/contact/:id',
        name: 'contact',
        component: Contact,
        hidden: true
    },
    // {
    //     path: '/contact/:id',
    //     name: 'contact',
    //     component: Contact
    // },
    {
        path: '/404',
        component: () =>
            import('@/views/page/404'),
        hidden: true
    },
]

const createRouter = () => new Router({
    mode: 'hash',
    scrollBehavior: () => ({
        y: 0
    }),
    routes: constantRoutes
})
const router = createRouter()

export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}

const _import = require('./_import_' + process.env.NODE_ENV) // 获取组件的方法

function filterAsyncRouter(asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
    // console.log(asyncRouterMap,'asyncRouterMap')
    if (!asyncRouterMap || !asyncRouterMap.filter) {
        return [];
    }
    
    const accessedRouters = asyncRouterMap.filter(route => {
        if (route.component) {
            if (route.component === 'Layout') { // Layout组件特殊处理
                route.component = LayoutPage
            } else {
                route.component = _import(route.component)
                // console.log(route.component, 123)
            }
        } else {
            route.component = {
                render: (e) => e("router-view")
            }
        }
        if (route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })

    return accessedRouters
}
import LayoutPage from '@/views/common/Home' // Layout 是架构组件，不在后台返回，在文件里单独引入
// import Layout from '@/components/common/Home';


var getRouter //  用来获取后台
router.beforeEach((to, from, next) => {
    if (!getRouter && getToken()) { // 不加这个判断，路由会陷入死循环 （如果没有路由）
        // if (!getObjArr('router')) { // 缓存里没有路由，axios重新获取
        //     getMenus().then(res => {
        //         if (res.data) {
        //             saveObjArr('router', res.data)
        //                 //存储路由到localStorage
        //             getRouter = getObjArr('router') //拿到路由
        //             routerGo(to, next) // 
        //         }
        //     })
        // } else { //  从localStorage拿到了路由
        //     getRouter = getObjArr('router') //拿到路由
        //     routerGo(to, next) //  //  添加路由  执行路由跳转方法
        // }
        getRouter = getObjArr('router') //拿到路由
        routerGo(to, next) //  //  添加路由  执行路由跳转方法
    } else if (!getToken() && to.path !== '/login') {
        next("/login")
    } else {
        next()
    }
})

// routerGo
function routerGo(to, next) {
    // 这里后端返回的数据getRouter  可能不是我们需要的结构，那么需要先有一步转换的步骤
    // 直到转换成前面第一步那种vue标准路由表的格式
    getRouter = filterAsyncRouter(getRouter) // 过滤路由  转换路由的component   
    // filterAsyncRoute方法是把后端返回的路由数据 转换为前端要的路由结构
    getRouter.push({
        path: '*',
        redirect: '/404',
        hidden: true
    });
    router.addRoutes(getRouter) //动态添加路由
    global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
    next({
        ...to,
        replace: true
    })
}

export default router